/*================================================================
*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称：sem.cpp
*   创 建 者：Ann
*   创建日期：2020年06月13日
*   描    述：
*
================================================================*/

//1.创建循环队列
//2.创建线程（生产者线程，消费者线程）
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <vector>

#define VECSIZE 4
#define THREADCOUNT 1

class RingQueue
{
    public:
        RingQueue()
            :Vec_(VECSIZE)
        {
            Capacity_ = VECSIZE;
            PosRead_ = 0;
            PosWrite_ = 0;

            sem_init(&Lock_, 0, 1);
            sem_init(&Product_Sem_, 0, VECSIZE);
            sem_init(&Consume_Sem_, 0, 0);
        }

        ~RingQueue()
        {
            sem_destroy(&Lock_);
            sem_destroy(&Product_Sem_);
            sem_destroy(&Consume_Sem_);
        }

        void Push(int& data)
        {
            sem_wait(&Product_Sem_);
            //加锁保护
            sem_wait(&Lock_);
            //1.写
            Vec_[PosWrite_] = data;
            //2.更新下一个写的位置
            PosWrite_ = (PosWrite_ + 1) % Capacity_;
            sem_post(&Lock_);
            sem_post(&Consume_Sem_);
        }

        void Pop(int* data)
        {
            sem_wait(&Consume_Sem_);
            sem_wait(&Lock_);
            //1.读
            *data = Vec_[PosRead_];
            //2.更新下一次读的位置
            PosRead_ = (PosRead_ + 1) % Capacity_;
            sem_post(&Lock_);
            sem_post(&Product_Sem_);
        }
    private:
        std::vector<int> Vec_;
        size_t Capacity_;

        //读写位置
        int PosWrite_;
        int PosRead_;

        //互斥
        sem_t Lock_;

        //同步
        sem_t Product_Sem_;
        sem_t Consume_Sem_;
};

void* Consume_start(void* arg)
{
    RingQueue* rq = (RingQueue*)arg;
    while(1)
    {
        int data;
        rq->Pop(&data);
        printf("Consume_start [%p][%d]\n", pthread_self(), data);
    }
    return NULL;
}

void* Product_start(void* arg)
{
    RingQueue* rq = (RingQueue*)arg;
    int i = 0;
    while(1)
    {
        rq->Push(i);
        printf("Product_start [%p][%d]\n", pthread_self(), i);
        i++;
    }
    return NULL;
}

int main()
{
    RingQueue* rq = new RingQueue();
    pthread_t con_tid[THREADCOUNT], pro_tid[THREADCOUNT];
    int i = 0;
    for(; i < THREADCOUNT; i++)
    {
        int ret = pthread_create(&con_tid[i], NULL, Consume_start, (void*)rq);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
        ret = pthread_create(&pro_tid[i], NULL, Product_start, (void*)rq);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }

    for(i = 0; i < THREADCOUNT; i++)
    {
        pthread_join(con_tid[i], NULL);
        pthread_join(pro_tid[i], NULL);
    }
    delete rq;
    return 0;
}
